#include <gpiod.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "record.h"
#include "wake.h"

#define GPIO_LINE 9

int main(void) {
    struct gpiod_chip *chip;
    struct gpiod_line *line;
    int value, last_value;
    int recording = 0;

    chip = gpiod_chip_open_by_label("GPIOF");
    if (!chip) {
        perror("打开GPIO芯片失败");
        return 1;
    }

    line = gpiod_chip_get_line(chip, GPIO_LINE);
    if (!line) {
        perror("获取GPIO线失败");
        gpiod_chip_close(chip);
        return 1;
    }

    if (gpiod_line_request_input(line, "key1")) {
        perror("请求将GPIO线设置为输入模式失败");
        gpiod_chip_close(chip);
        return 1;
    }

    last_value = gpiod_line_get_value(line);

    while (1) {
        value = gpiod_line_get_value(line);

        if (value != last_value) {
            if (value == 0) {
                printf("key pressed\n");
                if (recording == 0) {
                    printf("启动唤醒监听\n");
                    wake();
                    printf("wake结束\n");
                    recording = 1;
                } else {
                    printf("停止唤醒监听\n");
                    recording = 0;
                }
            }
            last_value = value;
        }
        usleep(100000);
    }

    gpiod_line_release(line);
    gpiod_chip_close(chip);
    return 0;
}
